import tkinter as tk
from tkinter import ttk, filedialog, messagebox
import os
import win32com.client
import pythoncom

class WordToPDFConverter:
    def __init__(self, root):
        self.root = root
        self.root.title("Word转PDF转换器")
        self.root.geometry("500x150")
        
        self.setup_ui()
    
    def setup_ui(self):
        main_frame = ttk.Frame(self.root, padding="20")
        main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
        
        # 文件选择
        file_frame = ttk.Frame(main_frame)
        file_frame.grid(row=0, column=0, columnspan=2, sticky=(tk.W, tk.E), pady=10)
        
        self.file_path = tk.StringVar()
        ttk.Label(file_frame, text="Word文档路径:").grid(row=0, column=0, sticky=tk.W)
        ttk.Entry(file_frame, textvariable=self.file_path, width=50).grid(row=1, column=0, sticky=(tk.W, tk.E), padx=(0, 10))
        ttk.Button(file_frame, text="浏览", command=self.browse_file).grid(row=1, column=1)
        
        # 转换按钮
        ttk.Button(main_frame, text="转换为PDF", command=self.convert_to_pdf).grid(row=1, column=0, columnspan=2, pady=20)
        
        # 进度条
        self.progress = ttk.Progressbar(main_frame, mode='indeterminate')
        self.progress.grid(row=2, column=0, columnspan=2, sticky=(tk.W, tk.E))
        
        # 状态标签
        self.status_label = ttk.Label(main_frame, text="请选择Word文档")
        self.status_label.grid(row=3, column=0, columnspan=2)
        
        # 配置权重
        self.root.columnconfigure(0, weight=1)
        self.root.rowconfigure(0, weight=1)
        main_frame.columnconfigure(0, weight=1)
        file_frame.columnconfigure(0, weight=1)
    
    def browse_file(self):
        filetypes = [
            ("Word文档", "*.docx *.doc"),
            ("所有文件", "*.*")
        ]
        filename = filedialog.askopenfilename(
            title="选择Word文档",
            filetypes=filetypes
        )
        if filename:
            self.file_path.set(filename)
            self.status_label.config(text=f"已选择: {os.path.basename(filename)}")
    
    def convert_to_pdf(self):
        if not self.file_path.get():
            messagebox.showerror("错误", "请先选择Word文档")
            return
        
        word_path = self.file_path.get()
        if not word_path.lower().endswith(('.doc', '.docx')):
            messagebox.showerror("错误", "请选择Word文档(.doc或.docx格式)")
            return
        
        try:
            self.progress.start()
            self.status_label.config(text="正在转换...")
            self.root.update()
            
            # 使用win32com调用Word进行转换
            output_path = self.convert_using_word(word_path)
            
            self.progress.stop()
            self.status_label.config(text="转换完成!")
            messagebox.showinfo("成功", f"PDF文件已生成:\n{output_path}")
            
        except Exception as e:
            self.progress.stop()
            self.status_label.config(text="转换失败")
            messagebox.showerror("错误", f"转换失败:\n{str(e)}")
    
    def convert_using_word(self, word_path):
        """使用Microsoft Word进行转换"""
        pythoncom.CoInitialize()  # 初始化COM库
        
        try:
            # 创建Word应用实例
            word = win32com.client.Dispatch("Word.Application")
            word.Visible = False  # 不显示Word界面
            
            # 打开文档
            doc = word.Documents.Open(word_path)
            
            # 生成输出路径
            base_name = os.path.splitext(word_path)[0]
            output_path = base_name + ".pdf"
            
            # 导出为PDF
            doc.SaveAs(output_path, FileFormat=17)  # 17代表PDF格式
            
            # 关闭文档和应用
            doc.Close()
            word.Quit()
            
            return output_path
            
        finally:
            pythoncom.CoUninitialize()  # 清理COM库

def main():
    root = tk.Tk()
    app = WordToPDFConverter(root)
    root.mainloop()

if __name__ == "__main__":
    main()